package sdk

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry"
)

/*
	通道管理
 */
type Channel struct {
	mgmtCli   *resmgmt.Client
	ordererId string
	channelId string
}

/*
	创建通道
 */
func (m *Channel) CreateChannel(channelTx string) error {
	req := resmgmt.SaveChannelRequest{ChannelID: m.channelId, ChannelConfigPath: channelTx}
	txID, err := m.mgmtCli.SaveChannel(req, resmgmt.WithOrdererEndpoint(m.ordererId))
	if err != nil || txID.TransactionID == "" {
		return err
	}
	fmt.Println("通道已成功创建")
	return nil
}

/**
	peer加入通道
 */
func (m *Channel) JoinChannel() error {
	if err := m.mgmtCli.JoinChannel(m.channelId, resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint(m.ordererId)); err != nil {
		return err
	}
	return nil
}
